//
//  BaseViewController.m
//  Project
//
//  Created by liting on 2025/8/29.
//

#import "BaseViewController.h"

@interface BaseViewController ()

@property (nonatomic, strong) UILabel *nativeLabel;

@end

@implementation BaseViewController

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTranslucent:NO];
    [self setupBaseConfiguration];
    [self setupCustomNavigationBar];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 隐藏系统导航栏
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 显示系统导航栏
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

#pragma mark - 基础配置
- (void)setupBaseConfiguration {
    self.view.backgroundColor = [UIColor whiteColor];
    self.currentPage = 1;
    self.hasMoreData = YES;

    // 禁用系统导航栏返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

#pragma mark - 自定义导航栏
- (void)setupCustomNavigationBar {
    _customNavBar = [[UIView alloc] init];
    _customNavBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_customNavBar];

    // 布局
    _customNavBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,
                                     [self navBarHeight]);

    // 返回按钮
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_customNavBar addSubview:_backButton];
    _backButton.frame = CGRectMake(12, [self statusBarHeight] + 7, 30, 30);

    // 标题
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont boldSystemFontOfSize:18];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_customNavBar addSubview:_titleLabel];
    _titleLabel.frame = CGRectMake(60, [self statusBarHeight],
                                   [UIScreen mainScreen].bounds.size.width - 120, 44);

    // 底部线条
    _navBottomLine = [[UIView alloc] init];
    _navBottomLine.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    [_customNavBar addSubview:_navBottomLine];
    _navBottomLine.frame = CGRectMake(0, [self navBarHeight] - 0.5,
                                      [UIScreen mainScreen].bounds.size.width, 0.5);
}

- (CGFloat)navBarHeight {
    return [self statusBarHeight] + 44;
}

- (CGFloat)statusBarHeight {
    if (@available(iOS 13.0, *)) {
        UIWindowScene *windowScene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
        return windowScene.statusBarManager.statusBarFrame.size.height;
    } else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}

- (void)setNavTitle:(NSString *)title {
    self.titleLabel.text = title;
}

- (UIButton *)addRightButtonWithTitle:(nullable NSString *)title
                                image:(nullable UIImage *)image
                               action:(SEL)action {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    if (title) {
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    if (image) {
        [button setImage:image forState:UIControlStateNormal];
    }
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [self.customNavBar addSubview:button];

    // 布局
    CGFloat buttonWidth = 44;
    CGFloat buttonX = [UIScreen mainScreen].bounds.size.width - buttonWidth - 12;
    button.frame = CGRectMake(buttonX, [self statusBarHeight], buttonWidth, 44);

    return button;
}

- (void)backButtonClicked {
    [self backToPreviousViewController];
}

#pragma mark - 表格视图懒加载
- (UITableView *)setupTableViewWithStyle:(UITableViewStyle)style {
    if (!_tableView) {
        CGFloat y = [self navBarHeight];
        CGFloat height = [UIScreen mainScreen].bounds.size.height - y;
        if (self.tabBarController && !self.tabBarController.tabBar.hidden) {
            height -= self.tabBarController.tabBar.frame.size.height;
        }

        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, y,
                                                                   [UIScreen mainScreen].bounds.size.width,
                                                                   height)
                                                  style:style];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.estimatedRowHeight = 44;
        _tableView.rowHeight = UITableViewAutomaticDimension;

        // 自动适配iOS15+
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }

        [self.view addSubview:_tableView];
        [self.view sendSubviewToBack:_tableView];
    }
    return _tableView;
}

- (UICollectionView *)setupCollectionViewWithLayout:(UICollectionViewLayout *)layout {
    if (!_collectionView) {
        if (!layout) {
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            flowLayout.minimumInteritemSpacing = 10;
            flowLayout.minimumLineSpacing = 10;
            flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
            layout = flowLayout;
        }

        CGFloat y = [self navBarHeight];
        CGFloat height = [UIScreen mainScreen].bounds.size.height - y;
        if (self.tabBarController && !self.tabBarController.tabBar.hidden) {
            height -= self.tabBarController.tabBar.frame.size.height;
        }

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, y,
                                                                             [UIScreen mainScreen].bounds.size.width,
                                                                             height)
                                             collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;

        [self.view addSubview:_collectionView];
        [self.view sendSubviewToBack:_collectionView];
    }
    return _collectionView;
}


#pragma mark - 标识视图懒加载
- (UILabel *)setupNativeLabel{
    if (!_nativeLabel) {
        _nativeLabel = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2-50, [UIScreen mainScreen].bounds.size.height/2-18,100,36)];
        _nativeLabel.backgroundColor = UIColor.blueColor;
        _nativeLabel.text = @"iOS 页面";
        _nativeLabel.textAlignment = NSTextAlignmentCenter;
        _nativeLabel.textColor = [UIColor whiteColor];
        _nativeLabel.layer.cornerRadius = 4;
        _nativeLabel.layer.masksToBounds = true;
        [self.view addSubview:_nativeLabel];
    }
    return _nativeLabel;
}


/**
 隐藏返回按钮
 */
- (void)hiddenBackBtn{
    self.backButton.hidden = YES;
}

#pragma mark - 刷新加载功能
- (void)addRefreshHeaderWithScrollView:(UIScrollView *)scrollView {
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        weakSelf.hasMoreData = YES;
        [weakSelf loadNewData];
    }];

    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    scrollView.mj_header = header;
}

- (void)addLoadMoreFooterWithScrollView:(UIScrollView *)scrollView {
    __weak typeof(self) weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage++;
        [weakSelf loadMoreData];
    }];

    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];

    scrollView.mj_footer = footer;
}

- (void)beginRefreshing {
    if (self.tableView && self.tableView.mj_header) {
        [self.tableView.mj_header beginRefreshing];
    } else if (self.collectionView && self.collectionView.mj_header) {
        [self.collectionView.mj_header beginRefreshing];
    }
}

- (void)endRefreshing {
    if (self.tableView && self.tableView.mj_header) {
        [self.tableView.mj_header endRefreshing];
    }
    if (self.collectionView && self.collectionView.mj_header) {
        [self.collectionView.mj_header endRefreshing];
    }

    if (self.tableView && self.tableView.mj_footer) {
        if (self.hasMoreData) {
            [self.tableView.mj_footer endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
    if (self.collectionView && self.collectionView.mj_footer) {
        if (self.hasMoreData) {
            [self.collectionView.mj_footer endRefreshing];
        } else {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    }
}

- (void)endRefreshingWithNoMoreData {
    self.hasMoreData = NO;
    if (self.tableView && self.tableView.mj_footer) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    if (self.collectionView && self.collectionView.mj_footer) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    }
}

- (void)resetNoMoreData {
    self.hasMoreData = YES;
    if (self.tableView && self.tableView.mj_footer) {
        [self.tableView.mj_footer resetNoMoreData];
    }
    if (self.collectionView && self.collectionView.mj_footer) {
        [self.collectionView.mj_footer resetNoMoreData];
    }
}

#pragma mark - 页面导航方法
- (void)backToPreviousViewController {
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        } else if (self.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    } else if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)backToViewControllerWithClassName:(NSString *)className {
    if (!self.navigationController) return;

    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:NSClassFromString(className)]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    // 没找到则返回上一页
    [self backToPreviousViewController];
}

- (void)backToRootViewController {
    if (self.navigationController) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - 子类重写的方法（空实现，子类根据需要重写）
- (void)loadNewData {
    // 子类重写
}

- (void)loadMoreData {
    // 子类重写
}

#pragma mark - 内存管理
- (void)dealloc {
    NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}

@end
